package com.ctyun.oos.cilent.controller;

import com.ctyun.oos.cilent.OosClient;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @Author：wk
 * @Create：2022/1/19/14:04
 * @Description：TODO
 * @Version：1.0
 */
@RestController
public class UploadController {

    @Autowired
    private OosClient oosClient;

    /**
     * 上传图片到Oss
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @PostMapping("/api/file/upload")
    public String uploadImg(MultipartFile multipartFile) throws IOException {
        InputStream fileContent = multipartFile.getInputStream();
        String fileName = multipartFile.getOriginalFilename();
//            图片存储地址/按月创建和存储图片
        String remotePath = dateToString(new Date(), "yyyy-MM");
        String path = oosClient.uploadFile(fileContent, remotePath, fileName);
//        Boolean path = oosClient.deleteFile(remotePath, fileName);
//        oosClient.putObject(fileContent, remotePath, fileName);
        return path.toString();
    }

    /**
     * 天翼云图片下载
     * @param key      文件名称
     * @return 下载结果提示，使用响应对象带回文件流
     */
    @GetMapping("api/oos/fileDown")
    public String fileDown(String key) {
        oosClient.downloadFile(key);
        return "下载图片成功";
    }




    /**
     * 时间对象转化为字符串
     *
     * @param date    时间对象
     * @param pattern 转换格式
     * @return 时间字符串
     */
    public static String dateToString(Date date, String pattern) {
        if (Objects.isNull(date) || org.apache.commons.lang3.StringUtils.isBlank(pattern)) {
            throw new IllegalArgumentException("请传递正确的参数");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }


}
